import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

class IconItem {
  final String name;
  final String code;

  IconItem(this.name, this.code);
}

class IconModel {
  static bool isTransFile = false;
  static ValueNotifier<int> transStepNotifier = ValueNotifier<int>(0);

  late String cacheDir;

  IconModel() {
    cacheDir = Directory.current.absolute.path +
        Platform.pathSeparator +
        'fonts' +
        Platform.pathSeparator;
  }

  init() async {
    await checkDirectory();

    return true;
  }

  Future<List<IconFileItem>> getFiles() async {
    print('查找历史文件');
    List<IconFileItem> files = [];
    List<FileSystemEntity> feList = Directory(cacheDir).listSync();
    bool hasUnTransFile = false;
    for (FileSystemEntity file in feList) {
      if (file.path.endsWith('.ttf') || file.path.endsWith('.otf')) {
        var item = IconFileItem(file.path);
        await item.check();
        files.add(item);
        if (!item.isReady && item.error.isEmpty) {
          hasUnTransFile = true;
        }
      }
    }
    if (!isTransFile && hasUnTransFile) {
      startTransFile();
    }
    print('共找到${files.length}');
    return files;
  }

  Future checkDirectory() async {
    if (!Directory(cacheDir).existsSync()) {
      Directory(cacheDir).createSync();
    }
  }

  Future<bool> placeFile(String file, [bool force = false]) async {
    String newPath =
        cacheDir + file.substring(file.lastIndexOf(Platform.pathSeparator) + 1);
    if (File(newPath).existsSync()) {
      if (force == false) {
        return false;
      } else {
        await deleteFile(newPath);
      }
    }

    File(file).copy(newPath);
    transStepNotifier.value++;
    if (!isTransFile) startTransFile();
    return true;
  }

  Future deleteFile(String file) async {
    if (File(file).existsSync()) {
      File(file).deleteSync();
    }
    IconFileItem item = IconFileItem(file);
    await item.check();
    if (item.isReady) {
      File(item.ttxFile).deleteSync();
    } else {
      String errorFile = file.replaceFirst(RegExp(r'\.[ot]tf$'), '.error');
      File(errorFile).deleteSync();
    }
  }

  void startTransFile() async {
    isTransFile = true;
    print('transfile');

    List<FileSystemEntity> feList = Directory(cacheDir).listSync();

    for (FileSystemEntity file in feList) {
      if (file.path.endsWith('.ttf') || file.path.endsWith('.otf')) {
        var item = IconFileItem(file.path);
        await item.check();
        if (!item.isReady && item.error.isEmpty) {
          try {
            final result = await Process.run(
                'ttx',
                [
                  item.file.substring(
                      item.file.lastIndexOf(Platform.pathSeparator) + 1)
                ],
                workingDirectory: cacheDir,
                stdoutEncoding: const Utf8Codec());
            print(result.exitCode);
            print(result.stdout.toString());
            transStepNotifier.value++;
            startTransFile();
          } on Exception catch (e) {
            print(e);
          }
          return;
        }
      }
    }

    isTransFile = false;
  }
}

class IconFileItem {
  String file;
  late String name;
  String ttxFile = '';
  bool isReady = false;
  String error = '';
  IconFileItem(this.file);

  Future check() async {
    ttxFile = file.replaceFirst(RegExp(r'\.[ot]tf$'), '.ttx');
    name = file.substring(
        file.lastIndexOf(Platform.pathSeparator) + 1, file.lastIndexOf('.'));
    String errorFile = file.replaceFirst(RegExp(r'\.[ot]tf$'), '.error');
    if (File(ttxFile).existsSync()) {
      isReady = true;
    }
    if (File(errorFile).existsSync()) {
      if (isReady) {
        File(errorFile).deleteSync();
      } else {
        error = File(errorFile).readAsStringSync();
      }
    }
  }
}
